package cn.iocoder.an.module.mold.controller.admin.workstation.stockio;

import cn.iocoder.an.framework.common.pojo.CommonResult;
import cn.iocoder.an.framework.common.pojo.PageResult;
import cn.iocoder.an.framework.common.util.object.BeanUtils;
import cn.iocoder.an.framework.tenant.core.aop.TenantIgnore;
import cn.iocoder.an.module.mold.controller.admin.account.vo.AccountPageReqVO;
import cn.iocoder.an.module.mold.controller.admin.account.vo.AccountRespVO;
import cn.iocoder.an.module.mold.controller.admin.drawingno.vo.DrawingNoPageReqVO;
import cn.iocoder.an.module.mold.controller.admin.drawingno.vo.DrawingNoRespVO;
import cn.iocoder.an.module.mold.controller.admin.stockiorecords.vo.StockIoRecordsSaveReqVO;
import cn.iocoder.an.module.mold.controller.admin.workstation.stockio.vo.StockIoBatchUpdateReqVO;
import cn.iocoder.an.module.mold.controller.admin.workstation.stockio.vo.StockIoPageReqVO;
import cn.iocoder.an.module.mold.dal.dataobject.account.AccountDO;
import cn.iocoder.an.module.mold.dal.dataobject.drawingno.DrawingNoDO;
import cn.iocoder.an.module.mold.service.account.AccountService;
import cn.iocoder.an.module.mold.service.drawingno.DrawingNoService;
import cn.iocoder.an.module.mold.service.stockiorecords.StockIoRecordsService;
import cn.iocoder.an.module.mold.service.workstation.stockio.StockIoService;
import cn.iocoder.an.module.mold.utils.MoldStateUtils;
import cn.iocoder.an.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.an.module.system.service.user.AdminUserService;
import com.fhs.core.trans.anno.TransMethodResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.annotation.security.PermitAll;
import jakarta.validation.Valid;
import org.apache.poi.ss.formula.functions.LinearRegressionFunction;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

import static cn.iocoder.an.framework.common.pojo.CommonResult.success;


@Tag(name = "管理后台 - 工控机模具出入库操作")
@RestController
@RequestMapping("/mold/workstation/stockio")
@Validated
public class StockioController {
    @Resource
    private AdminUserService userService;

    @Resource
    private AccountService accountService;

    @Resource
    private DrawingNoService drawingNoService;

    @Resource
    private StockIoRecordsService stockIoRecordsService;


    @PermitAll
    @GetMapping("/login")
    @Operation(summary = "刷卡登录接口")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @TenantIgnore
    public CommonResult<AdminUserDO> getStockIoRecords(@RequestParam("card_number") String cardNumber, @RequestParam("tenant_id") String tenantId) {
        AdminUserDO user = userService.getUserByCardNumberAndTenantId(cardNumber, tenantId);
        return success(user);
    }

    @PermitAll
    @GetMapping("/page")
    @Operation(summary = "获得模具台账分页")
    @TransMethodResult
    public CommonResult<PageResult<DrawingNoRespVO>> getAccountList(@Valid DrawingNoPageReqVO pageReqVO) {
        //这里分页思路查出所有的模具，并根据图号进行分组
        PageResult<DrawingNoDO> pageResult = drawingNoService.getDrawingNoPage(pageReqVO);
        PageResult<DrawingNoRespVO> pageVoResult = BeanUtils.toBean(pageResult, DrawingNoRespVO.class);
        pageVoResult.getList().forEach(item -> {
            List<AccountDO> accounts = accountService.getAccountsByDrawingId(item.getId());
            item.setAccounts(BeanUtils.toBean(accounts, AccountRespVO.class));
        });
        return success(pageVoResult);
    }

/*
    @PermitAll
    @GetMapping("/page")
    @Operation(summary = "获得模具台账分页")
    @TransMethodResult
    public CommonResult<PageResult<AccountRespVO>> getAccountPage(@Valid DrawingNoPageReqVO pageReqVO) {
        //这里分页思路查出所有的模具，并根据图号进行分组
        PageResult<DrawingNoDO> pageResult = drawingNoService.getDrawingNoPage(pageReqVO);

        return success(BeanUtils.toBean(pageResult, AccountRespVO.class));
    }*/

    //出库
    @PermitAll
    @PutMapping("/account-status")
    @Operation(summary = "修改模具状态")
    @TransMethodResult
    public CommonResult<MoldStateUtils.ValidationResult> accountStatus(@RequestParam("user_id") Long userId, @RequestParam("account_id") Long accountId, @RequestParam("status") Integer status, @RequestParam("data") String data) {
        return success(modAcocuntStatus(userId, accountId, status, data));
    }


    //出库
    @PermitAll
    @PutMapping("/accounts-status")
    @Operation(summary = "修改多模具状态")
    public CommonResult<List<MoldStateUtils.ValidationResult>> accountsStatus(@Valid @RequestBody StockIoBatchUpdateReqVO batchUpdateReqVO) {
        List<MoldStateUtils.ValidationResult> results = batchUpdateReqVO.getAccountIds()
                .stream()
                .map(accountId -> modAcocuntStatus(batchUpdateReqVO.getUserId(), accountId, batchUpdateReqVO.getStatus(), batchUpdateReqVO.getData()))
                .toList();
        return success(results);
    }


    private MoldStateUtils.ValidationResult modAcocuntStatus(Long userId, Long accountId, Integer inventStatus, String data) {
        //查询account
        AccountDO accountDO = accountService.getAccount(accountId);
        MoldStateUtils.MoldState sourState = MoldStateUtils.MoldState.fromCode(accountDO.getInventoryStatus() + "_" + accountDO.getUsageStatus() + "_" + accountDO.getRepairStatus() + "_" + accountDO.getUpkeepStatus() + "_" + accountDO.getRecheckStatus());
        MoldStateUtils.ValidationResult result = MoldStateUtils.validateTransition(sourState, MoldStateUtils.MoldState.fromCode(inventStatus + "_" + accountDO.getUsageStatus() + "_" + accountDO.getRepairStatus() + "_" + accountDO.getUpkeepStatus() + "_" + accountDO.getRecheckStatus()));
        //根据结果判断是否执行下面操作
        if (result.isAllowed()) {
            //出库
            accountDO.setInventoryStatus(inventStatus);
            accountService.updateAccount(accountDO);
            //记录出入库数据
            StockIoRecordsSaveReqVO createReqVO = new StockIoRecordsSaveReqVO();
            createReqVO.setInOrOut(inventStatus);
            //获取最新记录的code
            createReqVO.setCode(stockIoRecordsService.getLastUnUsedCode(inventStatus));
            createReqVO.setDeptId(accountDO.getDeptId());
            createReqVO.setWarehouseId(accountDO.getWarehouseId());
            createReqVO.setStorageId(accountDO.getStorageId());
            createReqVO.setAccountId(accountId);
            createReqVO.setDrawingNoId(accountDO.getDrawingNoId());
            //操作人
            createReqVO.setOperatorId(userId);
            createReqVO.setOperateTime(accountDO.getUpdateTime());
            createReqVO.setDescription(data);
            stockIoRecordsService.createStockIoRecords(createReqVO);
        }
        return result;
    }

    @PermitAll
    @GetMapping("/drawingNos")
    @Operation(summary = "获得所有图号分类")
    public CommonResult<List<DrawingNoDO>> getDrawingNoAll() {
        return success(drawingNoService.getDrawingNoAll());
    }
}


